import { clearLoginStatus } from '../utils/auth';
import { baseUrl } from '../config';
import * as util from '../utils/util';
let app = getApp();

const request = (url, data, option = {
  method: 'POST',
  contentType: 'form'
}) => {
  let headers = {
    'Accept': 'application/json',
    'isDemo': '1'
  };
  const app = getApp();
  if (option.method === 'POST' && option.contentType === 'form') {
    headers['content-type'] = 'application/x-www-form-urlencoded';
  }
  const token = wx.getStorageSync('token');
  if (token) {
    headers['Authorization'] = token;
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      data: data,
      method: option.method || 'POST',
      header: headers,
      success: function (res) {
        // console.log(res, 999)
        wx.hideLoading();
        if (res.statusCode === 200){
          if (res.data && res.data.code===200) {
            // return reject('发生未知错误，请稍后再试');
            resolve(res.data);
          }else{
            wx.setStorage({
              key:"token",
              data:null,
              success: function(){
                app.globalData.userInfo.hasLogin=false
                util.toast (res.data.desc);
              }
            })
            // return reject(res.data.desc);
          }
        }else{
          // console.log(res.statusCode, '================')
          let msg = '';
            let status = res.statusCode || res.status
            // debugger
            switch (status) {
              case 400:
                msg = '错误请求';
                break;
              case 401:
                msg = '未授权，请重新登录';
                break;
              case 403:
                msg = '拒绝访问';
                break;
              case 404:
                msg = '请求错误,未找到该资源';
                break;
              case 405:
                msg = '请求方法未允许';
                break;
              case 408:
                msg = '请求超时';
                break;
              case 500:
                msg = '服务器端出错';
                break;
              case 501:
                msg = '网络未实现';
                break;
              case 502:
                msg = '网络错误';
                break;
              case 503:
                msg = '服务不可用';
                break;
              case 504:
                msg = '网络超时';
                break;
              case 505:
                msg = 'http版本不支持该请求';
                break;
              default:
                msg = `连接错误${status || ''}`;
            }
            wx.setStorage({
              key:"token",
              data:null,
              success: function(){
                app.globalData.userInfo.hasLogin=false
                util.toast (msg);
              }
            })
            // return reject(msg);
            // wx.showToast({
            //   title: msg,
            //   icon: 'none',
            //   duration: 2000
            // });
        } 
        // return reject('网络请求失败，请稍后再试');
        
        // if (data.head.status == 1) {
          // resolve(data);
        // } else if (data.head.errorCode === '999') {
        //   //退出登录 清除用户数据
        //   clearLoginStatus();
        //   wx.reLaunch({
        //     url: '/pages/login/login'
        //   });
        // } else {
          // reject(data.head.errorMsg);
        // }
      },
      fail: function (e) {
        // console.log(111111111)
        // wx.showToast({
        //       title: '网络请求失败，请稍后再试',
        //       icon: 'none',
        //       duration: 2000
        //     });
        // return reject('网络请求失败，请稍后再试');
        // wx.hideLoading();
        util.toast ('网络请求失败，请稍后再试');
      },
      complete: function (res) {
        // wx.hideLoading();
      }
    });
  });
};

const post = (url, data) => {
  return request(url, data, {
    method: 'POST',
    contentType: 'json'
  });
};

const put = (url, data) => {
  return request(url, data, {
    method: 'PUT',
    contentType: 'json'
  });
};

const delet = (url, data) => {
  return request(url, data, {
    method: 'DELETE',
    contentType: 'json'
  });
};

const postJson = (url, data) => {
  return request(url, data, {
    method: 'POST',
    contentType: 'form'
  });
};

const get = (url, data) => {
  if (!data) {
    data = {};
  }
  data.timestamp = new Date().getTime();
  return request(url, data, {
    method: 'GET'
  });
};

export {
  request,
  post,
  put,
  delet,
  postJson,
  get
}